package com.sky.service.user.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.exception.ParameterIsNullException;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetMealMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.Setmeal;
import com.sky.pojo.ShoppingCart;
import com.sky.service.user.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @Author:篍
 * @Date: 2025/08/25 20:50
 * @Description:
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetMealMapper setMealMapper;

    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    @Override
    public void add(ShoppingCartDTO shoppingCartDTO) {
        Long dishId = shoppingCartDTO.getDishId();
        Long setmealId = shoppingCartDTO.getSetmealId();
        String dishFlavor = shoppingCartDTO.getDishFlavor();
        //判空
        if (Objects.isNull(dishId)&&Objects.isNull(setmealId)){
            throw new ParameterIsNullException("必须选择菜品或者套餐");
        }
        Long userId = BaseContext.getCurrentId();
        //判断当前菜品或者套餐是否在购物车中
        ShoppingCart shoppingCart= shoppingCartMapper.selectRecord(userId,shoppingCartDTO);
        if (Objects.isNull(shoppingCart)){
            shoppingCart = ShoppingCart.builder()
                    .userId(userId)
                    .dishId(dishId)
                    .setmealId(setmealId)
                    .dishFlavor(dishFlavor)
                    .number(1)
                    .createTime(LocalDateTime.now())
                    .build();
            //是菜品还是套餐
            if (Objects.nonNull(dishId)){
                Dish dish = dishMapper.getById(dishId);
                shoppingCart.setAmount(dish.getPrice());
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
            }else {
                Setmeal setmeal = setMealMapper.findById(setmealId);
                shoppingCart.setAmount(setmeal.getPrice());
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
            }
            //插入
            save(shoppingCart);
        }else {
            //在购物车中
            shoppingCart.setNumber(shoppingCart.getNumber()+1);
            updateById(shoppingCart);
        }
    }
}
